const { app: getApp } = require('./app');
const dotenv = require('dotenv');
const path = require('path');
const LevelDBService = require('./services/LevelDBService');

// 根据环境加载不同的配置文件
const env = process.env.NODE_ENV || 'development';
dotenv.config({
  path: path.resolve(process.cwd(), `.env${env === 'production' ? '.production' : ''}`)
});

const PORT = process.env.PORT || 3000;
const BASE_PATH = process.env.BASE_PATH || '';

// 初始化股票信息
async function initializeStockData() {
  try {
    // 等待数据库完全初始化
    await new Promise(resolve => setTimeout(resolve, 1000));
    await LevelDBService.initializeStockInfo();
    console.log('Stock data initialized successfully');
  } catch (error) {
    console.error('Error initializing stock data:', error);
  }
}

getApp.then(async app => {
  // 等待应用完全初始化后再初始化股票数据
  setTimeout(async () => {
    await initializeStockData();
  }, 2000);
  
  app.listen(PORT, () => {
    console.log(`Stock Quant Trading System server is running on port ${PORT}`);
    console.log(`Base path: ${BASE_PATH || '/'}`);
  });
}).catch(error => {
  console.error('Failed to start server:', error);
  process.exit(1);
});